﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Zen4SyncDashboard.DAL;
using System.Collections.ObjectModel;
using System.Threading.Tasks;

namespace Zen4SyncDashboard.ViewModel
{
    public class MergeSyncContextViewModel : BaseViewModel
    {
        #region - Bound Properties -

        public ObservableCollection<validateType> ValidateTypes { get; private set; }

        public ObservableCollection<syncSessionContext> SyncSessionContexts { get; private set; }

        public syncSessionContext NewSyncSessionContext { get; private set; }
        public subscriber NewSubscriber { get; private set; }

        #endregion - Bound Properties -

        #region - Commands -

        public RelayCommand AddNewSyncSessionContextCommand { get; private set; }

        #endregion - Commands -

        public MergeSyncContextViewModel()
        {
            InitializeBoundProperties();
            InitializeCommands();
        }

        #region - Initialization Methods -

        private void InitializeBoundProperties()
        {
            NewSyncSessionContext = Zen4SyncModel.SyncSessionContext.Create();
            NewSubscriber = Zen4SyncModel.Subscriber.Create();

            Task.Factory
                .StartNew(() =>
                {
                    base.SetWorkStatus(true);

                    base.SetWorkStatus("Fetching Validate Types...");
                    ValidateTypes = Zen4SyncModel.ValidateType.GetAll();
                    base.OnPropertyChanged("ValidateTypes");

                    base.SetWorkStatus("Fetching Merge Synchronization Contexts...");
                    SyncSessionContexts = Zen4SyncModel.SyncSessionContext.GetAll();
                    base.OnPropertyChanged("SyncSessionContexts");

                    base.SetWorkStatus(false);
                });
        }

        private void InitializeCommands()
        {
            AddNewSyncSessionContextCommand = new RelayCommand(
                param => AddNewSyncSessionContext(),
                param => CanAddNewSyncSessionContext());
        }

        private bool CanAddNewSyncSessionContext()
        {
            return NewSubscriber.IsValid() && NewSyncSessionContext.IsValid();
        }

        private void AddNewSyncSessionContext()
        {
            NewSyncSessionContext.subscriber = NewSubscriber;
            
            Zen4SyncModel.SyncSessionContext.Add(NewSyncSessionContext);

            SyncSessionContexts.Add(NewSyncSessionContext);

            NewSubscriber = Zen4SyncModel.Subscriber.Create();
            base.OnPropertyChanged("NewSubscriber");

            NewSyncSessionContext = Zen4SyncModel.SyncSessionContext.Create();
            base.OnPropertyChanged("NewSubscriber");
        }

        #endregion - Initialization Methods -
    }
}
